from rest_framework import serializers
from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate
from .models import Profile
from system.models import Role

class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = '__all__'  # 取model中所有的字段。如果只是取部分，就 ("a","b") 元组的方式

class ProfileSerializer(serializers.ModelSerializer):
    token = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()
    role_list = RoleSerializer(many=True, read_only=True,source='get_role_list')
    class Meta:
        model = Profile
        fields = '__all__'  # 取model中所有的字段。如果只是取部分，就 ("a","b") 元组的方式

    def get_token(self, obj):
        user = obj.user
        token, is_create = Token.objects.get_or_create(user=user)

        return token.key

    def get_user(self, obj):
        return obj.user_id


    def get_role_list(self, obj):
        return obj.role_list

class LoginSerializer(serializers.Serializer):  # 登录
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)

    def validate_username(self, data): # 只校验了 username
        return data

    def validate_password(self, data): # 只校验了 password
        return data

    def validate(self,attrs): # 校验全部字段
        username = attrs["username"]
        password = attrs["password"]

        user = authenticate(username=username, password=password)

        if not user:
            raise serializers.ValidationError("用户名或密码不正确")
        else:
            Profile.objects.get_or_create(user=user)  # 登录成功时，自动为用户创建 个人资料
            Token.objects.get_or_create(user=user)  # 登录时就获取token

            attrs["user"] = user
            return attrs


class ResetPassSerializer(serializers.Serializer):  # 修改密码
    new_password = serializers.CharField(required=True,min_length=6)
    confirm_password = serializers.CharField(required=True,min_length=6)

    def validate(self, attrs):
        new_password = attrs["new_password"]
        confirm_password = attrs["confirm_password"]

        if new_password != confirm_password:
            raise serializers.ValidationError("密码和确认密码不一致")

        return attrs